﻿function HTMLCollectionToArray(content, skipFirst) {
    if (skipFirst) {
        var array = new Array(content.length - 1);
        for (var i = 1; i < content.length; i++) {
            array[i - 1] = content[i];
        }
        return array;
    }
    else {
        var array = new Array(content.length);
        for (var i = 0; i < content.length; i++) {
            array[i] = content[i];
        }
        return array;
    }
}

function accentsTidy(s) {
    var r = s.toLowerCase();
    r = r.replace(new RegExp(/\s/g), "");
    r = r.replace(new RegExp(/[àáâãäå]/g), "a");
    r = r.replace(new RegExp(/æ/g), "ae");
    r = r.replace(new RegExp(/ç/g), "c");
    r = r.replace(new RegExp(/[èéêë]/g), "e");
    r = r.replace(new RegExp(/[ìíîï]/g), "i");
    r = r.replace(new RegExp(/ñ/g), "n");
    r = r.replace(new RegExp(/[òóôõö]/g), "o");
    r = r.replace(new RegExp(/œ/g), "oe");
    r = r.replace(new RegExp(/[ùúûü]/g), "u");
    r = r.replace(new RegExp(/[ýÿ]/g), "y");
    r = r.replace(new RegExp(/\W/g), "");
    r = r.replace(new RegExp(/'/g), "");
    return r;
};

function person(row) {

    var cols = row.childNodes;
    var full_name = cols[1].textContent;
    var name_parts = full_name.split(" ");

    var person =
        {
            FullName: full_name//, 
            //Surname: name_parts[0],
            //Name: name_parts[1]
        };
    try {
        person.Url = cols[4].childNodes[0].childNodes[0].getElementsByTagName('a')[0].href;
    } catch (e) {
    }
    return person;
}

function GetTableRows() {
    var table = document.getElementsByClassName("flexible generaltable generalbox")[0];
    return table.getElementsByTagName("tbody")[0].childNodes;
}

function GetTableEntries() {
    var entries = GetTableRows();
    var files = new Array();
    for (var i = 1; i < entries.length; i++) {
        var row = entries[i];
        var row_obj = person(row);
        if (row_obj.Url != null) {
            files.push(row_obj);
        }
    }
    chrome.runtime.sendMessage(files);
    return files;
}

function PrettyRow(row) {

    var cols = row.childNodes;
    var full_name = cols[2].textContent;
    var name_parts = full_name.split(" ");

    var p_row =
        {
            FullName: full_name//,
            //Surname: name_parts[0],
            //Name: name_parts[1]
        };

    p_row.SelectElement = cols[5].childNodes[4];
    p_row.Message = cols[11].childNodes[1];
    if (p_row.Message === undefined) {
        try {
            var c = cols[10].childNodes[0];
            p_row.Message = c.getElementsByTagName("TextArea")[0];
        }
        catch (e) {
        }
    }
    p_row.Submitted = cols[4].getElementsByClassName('submissionstatussubmitted').length != 0;
    console.log(p_row.FullName + "\t\t" + p_row.Submitted);
    return p_row;

}

function IsSame(stringA, stringB) {
    if (stringA.toLowerCase() == stringB.toLowerCase())
        return true;
    //var partsA = stringA.toLowerCase().split(" ");
    //var partsB = stringB.toLowerCase().split(" ");
    //if (partsA.length == partsB.length) {

    //}
    return false;
}

function GetMatchingRows(profile, rows, remove_accents) {
    var matches = [];
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        var r_name = remove_accents ? accentsTidy(row.FullName) : row.FullName;
        var p_name = remove_accents ? accentsTidy(profile.FullName.replace('_', ' ')) : profile.FullName.replace('_', ' ')
        if (IsSame(r_name, p_name)) {
            if (row.Submitted)
                matches.push(row);
        }
    }
    return matches;
    //alert("Not found: " + profile.FullName);
}

function SetMark(profile, rows) {
    var m_rows = GetMatchingRows(profile, rows);
    var row;
    if (m_rows.length > 1) {
        alert("Multiple submission for " + profile.FullName + "!!! Mark extended");
    }
    else if (m_rows.length < 1) {
        m_rows = GetMatchingRows(profile, rows, true);

        var names = "";
        for (var i = 0; i < m_rows.length; i++) {
            names += "\n" + m_rows[i].FullName
        }

        alert("Person " + profile.FullName + " has mark, but no submission... Searching deeper... Found" + names);

        //return;
    }

    for (var i = 0; i < m_rows.length; i++) {
        row = m_rows[i];
        var options = row.SelectElement;//HTMLCollectionToArray(rows[i - 1].SelectElement.getElementsByTagName('option'), false);
        //for (var j = 0; j < options.length; j++) {
        //    options[j].selected = null;
        //    if (profile.Mark == j - 1) {
        //        options[j].selected = "selected";
        //    }
        //}
        row.SelectElement.value = profile.Mark;
        if (profile.Message != null) {
            try {
                row.Message.value = profile.Message;
            } catch (e) {
                alert("comment not available for " + profile.FullName);
            }
        }
    }
}

function SetMarks(content) {
    try {
        var marks = JSON.parse(content);
        var rows_html = GetTableRows();
        var rows = new Array(rows_html.length - 1);
        for (var i = 1; i < rows_html.length; i++) {
            rows[i - 1] = PrettyRow(rows_html[i]);
            //rows[i - 1].SelectElement = HTMLCollectionToArray(rows[i - 1].SelectElement.getElementsByTagName('option')).sort(function (el) { return el.value; });
        }

        for (var i = 0; i < marks.length; i++) {
            SetMark(marks[i], rows);
        }

    } catch (e) {
        alert("Error in input string");
    }
}

function CreateAdditionalElements() {
    var div = document.createElement('div');
    div.id = "extensionAdded";

    var inputText = document.createElement("input");
    inputText.isTextEdit = true;
    inputText.value = "";
    inputText.id = "inputText";
    div.appendChild(inputText);

    var set_btn = document.createElement("BUTTON")
    set_btn.id = "setMarks";
    var t = document.createTextNode("Set marks");
    set_btn.appendChild(t);
    set_btn.onclick = function () {
        SetMarks(inputText.value);
        alert("Done set");
    }
    div.appendChild(set_btn);

    div.appendChild(document.createElement('br'));
    div.appendChild(document.createElement('br'));

    var fileJson = document.createElement("div");
    fileJson.id = "jsonContainer";

    /*var get_btn = document.createElement("BUTTON")
    get_btn.id = "getFiles";
    var t = document.createTextNode("Get files");
    get_btn.appendChild(t);
    get_btn.onclick = function () {
        var file_list = GetTableEntries();
        var text = document.createTextNode(JSON.stringify(file_list));
        fileJson.appendChild(text);
        //alert("Done");
    }*/
    //div.appendChild(get_btn);
    div.appendChild(fileJson);

    return div;
}

function Main() {
    var main_div = CreateAdditionalElements();
    document.body.appendChild(main_div);
}

Main();

